#include "QueryMicroMan.h"
#include <QStringList>

//-------------------------------------

QueryMicroMan::QueryMicroMan(QObject *parent) :
    QObject(parent),
    maxtimeout( 500 ),
    sock( new QTcpSocket( this ) ),
    timer( new QTimer( this ) )
{
    connect( timer, SIGNAL( timeout() ), this, SLOT( onTimeout() ) );
    //connect( sock, SIGNAL( connected() ), this, SLOT( onConnected() ) );
    connect( sock, SIGNAL( readyRead() ), this, SLOT( onReadyRead() ) );
}

//-------------------------------------

void QueryMicroMan::Connect( QString h, quint16 p )
{
    if( !sock->isOpen() )
    {
        if( sock->open( QIODevice::ReadWrite ) )
        {
            if( sock->state() == QAbstractSocket::UnconnectedState )
            {
                sock->connectToHost( h, p );
            }
            else
            {
                sock->close();
            }
        }
    }
}

//-------------------------------------

void QueryMicroMan::Disconnect()
{
    if( sock->isOpen() )
    {
        sock->close();
    }
}

//-------------------------------------
/*
void QueryMicroMan::onConnected()
{
    int cp=1;
}
*/
//-------------------------------------

void QueryMicroMan::ExecCmd( const QString cmd )
{
    mtx.lock();
    locked = true;
    outStr.clear();
    if( sock->state() == QAbstractSocket::ConnectedState )
    {
        timer->start( maxtimeout );
        sock->write( ( cmd + "\n" ).toAscii() );
    }
}

//-------------------------------------

void QueryMicroMan::onReadyRead()
{
    timer->stop();

    QTextStream stream( sock );
    QStringList sl;

    while( sock->bytesAvailable() )
    {
        sl = stream.readAll().split( "\n" );

        for( int i=0; i < sl.size()-1; ++i )
        {
            outStr = sl[i];
            emit updated( sl[i] );
        }
    }

    locked = false;
    mtx.unlock();
}

//-------------------------------------

void QueryMicroMan::onTimeout()
{
    timer->stop();
    emit updated( TIMEOUTED_STR );
}

//-------------------------------------
